const api = require("../../../api/mop");
const { err, toast, get } = require("../../../utils/wxapi");
Page({
  data: {
    // 开关
    checked: true,
    add_checked: false,
    // 岗位信息
    workName: "",
    workPers: "",
    workPlace: "",
    interviewAddress: "",
    interviewTime: "",
    longitude: Number,
    latitude: Number,
    remark: "",
    subsidyDate: "",
    policyDuration: "",
    income: "",
    sex: "",
    age: "",
    // 顶部图片数组
    listImage: [],
    typelist: [],
    workPay: "",
    subsidyCondition: "",
    subsidyAmount: "",
    paylist: ["男", "女", "男女不限"],
    form: [],
    id: "",
    role: get("user").role,
    userId: get("userId"),
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onLoad(e) {
    await this.gettype();
    if (e.id) {
      this.setData({ id: e.id });
      this.getId(this.data.id);
    }
  },

  async getId(id) {
    try {
      const res = await api.getwork({ id });
      if (res.respCode === 200) {
        const item = JSON.parse(res.source);
        const listImage = this.fluImg(item.workImgList);
        this.typefor(item.workTypeList);
        this.fluform(item.workContentList);
        this.flutate(item.state);
        this.setData({
          listImage,
          workName: item.workName,
          workPay: item.workPay,
          age: item.age,
          sex: item.sex,
          interviewAddress: item.interviewAddress,
          interviewTime: item.interviewTime,
          remark: item.remark,
          subsidyCondition: item.subsidyCondition,
          subsidyAmount: item.subsidyAmount,
          longitude: item.longitude,
          latitude: item.latitude,
        });
      }
    } catch (error) {
      err(error);
    }
  },
  flutate(e) {
    if (e == 1) {
      this.setData({ add_checked: true });
    } else if (e == 2) {
      this.setData({ add_checked: false });
    }
  },
  fluform(arr) {
    const { form } = this.data;
    arr.forEach((e) => {
      if (e.content) {
        let info = {
          title: "",
          item: [],
        };
        info.title = e.content;
        let conInfo = JSON.parse(e.contentInfo);
        for (const i in conInfo) {
          const obj = {};
          obj.key = i;
          obj.value = conInfo[i];
          info.item.push(obj);
        }
        form.push(info);
      }
    });
    this.setData({ form });
  },
  fluImg(img) {
    let image = [];
    img.forEach((e) => {
      image.push({ imgUrl: e.imgUrl });
    });
    return image;
  },
  pio() {
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        const { address, latitude, longitude } = res;
        this.setData({ interviewAddress: address, latitude, longitude });
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },
  select(e) {
    const i = e.detail.value;
    const { paylist } = this.data;
    this.setData({ sex: paylist[i] });
  },
  typefor(arr) {
    const { typelist } = this.data;
    arr.forEach((e) => {
      typelist.forEach((v) => {
        if (e.id === v.id) {
          v.sel = !v.sel;
        }
      });
    });
    this.setData({ typelist });
  },
  //岗位id
  async gettype() {
    try {
      const res = await api.work_type();
      const typelist = JSON.parse(res.source);
      this.setData({ typelist });
    } catch (error) {
      err(error);
    }
  },
  tapType(e) {
    let { item, i } = e.currentTarget.dataset;
    let { typelist } = this.data;
    item.sel = !item.sel;
    typelist[i] = item;
    this.setData({ typelist });
  },
  // 开关
  onChange(e) {
    this.setData({ checked: e.detail });
  },
  onChangeAdd(e) {
    this.setData({ add_checked: e.detail });
  },
  // 上传顶部轮播图片
  upImage() {
    wx.showLoading({ title: "上传中" });
    wx.chooseMedia({
      count: 9,
      success: (res) => {
        console.log(res);
        for (let i = 0; i < res.tempFiles.length; i++) {
          const img = res.tempFiles[i].tempFilePath;
          this.upLs(img);
          if (i == res.tempFiles.length - 1) {
            wx.hideLoading();
          }
        }
      },
      fail: (err) => {
        toast("上传失败");
        wx.hideLoading();
      },
    });
  },
  async upLs(img) {
    try {
      const fileName = Date.now() + ".jpg";
      const { fileID } = await wx.cloud.uploadFile({
        filePath: img,
        cloudPath: "image/" + fileName,
      });
      const data = { imgUrl: fileID };
      let { listImage } = this.data;
      listImage = [...listImage, data];
      this.setData({ listImage });
    } catch (error) {
      err(error);
      toast("上传失败");
      wx.hideLoading();
    }
  },
  // 添加新岗位
  async getAdd() {
    wx.showLoading({ title: "发布中" });
    try {
      const {
        workName,
        longitude,
        latitude,
        typelist,
        listImage,
        workPay,
        interviewTime,
        interviewAddress,
        subsidyCondition,
        subsidyAmount,
        add_checked,
        sex,
        age,
        remark,
        role,
        userId,
      } = this.data;
      const state = add_checked ? "1" : "2";
      const workTypeIdList = typelist.filter((e) => e.sel).map((e) => e.id);
      if (workTypeIdList.length === 0) {
        toast("请选择福利信息");
        return;
      }
      if (
        !workName ||
        !workPay ||
        !sex ||
        !age ||
        !longitude ||
        !latitude ||
        !interviewAddress ||
        !remark
      )
        return toast("请将页面信息填写完整");
      if (listImage.length === 0) return toast("请添加图片");
      let workInfo = {
        workName,
        longitude,
        latitude,
        interviewTime,
        interviewAddress,
        workPay,
        state,
        workTypeIdList,
        workImgList: listImage,
        subsidyCondition,
        subsidyAmount,
        sex,
        age,
        remark,
      };
      if (role == 3) {
        workInfo = {
          ...workInfo,
          userId,
        };
      }
      const info = this.obj();
      const data = { workInfo };
      const sumdata = Object.assign({}, data, info);
      const datas = JSON.stringify(sumdata);
      const res = await api.postwork(datas);
      if (res.respCode === 200) {
        wx.hideLoading();
        toast("发布成功，即将跳转");
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 2000);
      } else {
        toast("发布失败，请重新填写");
      }
    } catch (error) {
      err(error);
      toast("发布失败，请重新填写");
      throw error;
    }
  },
  async putAdd() {
    wx.showLoading({ title: "发布中" });
    try {
      const {
        workName,
        longitude,
        latitude,
        typelist,
        listImage,
        workPay,
        interviewTime,
        interviewAddress,
        subsidyCondition,
        subsidyAmount,
        add_checked,
        sex,
        age,
        remark,
        role,
        id,
      } = this.data;
      const state = add_checked ? "1" : "2";
      const workTypeIdList = typelist.filter((e) => e.sel).map((e) => e.id);
      if (workTypeIdList.length === 0) return toast("请选择福利信息");
      if (
        !workName ||
        !workPay ||
        !sex ||
        !age ||
        !longitude ||
        !latitude ||
        !interviewAddress ||
        !remark
      )
        return toast("请将页面必要信息填写完整");
      let workInfo = {
        workName,
        longitude,
        latitude,
        interviewTime,
        interviewAddress,
        workPay,
        state,
        workTypeIdList,
        workImgList: listImage,
        subsidyCondition,
        subsidyAmount,
        sex,
        age,
        remark,
        id,
      };
      if (role == 3) {
        workInfo = {
          ...workInfo,
          userId,
        };
      }
      const info = this.obj();
      const data = { workInfo };
      const sumdata = Object.assign({}, data, info);
      const datas = JSON.stringify(sumdata);
      const res = await api.putwork(datas);
      if (res.respCode === 200) {
        wx.hideLoading();
        toast("发布成功，即将跳转");
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 2000);
      } else {
        toast("发布失败，请重新填写");
      }
    } catch (error) {
      err(error);
      toast("发布失败，请重新填写");
      throw error;
    }
  },
  clone(e) {
    console.log(e);
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: "提示",
      content: "你确定将该张图片删除吗？",
      complete: (res) => {
        if (res.confirm) {
          const { listImage } = this.data;
          listImage.splice(index, 1);
          this.setData({ listImage });
        }
      },
    });
  },
  froms() {
    const { form } = this.data;
    form.push({
      title: "",
      item: [{ key: "", value: "" }],
    });
    this.setData({ form });
  },
  cutform(e) {
    const { form } = this.data;
    const { index } = e.currentTarget.dataset;
    form.splice(index, 1);
    this.setData({ form });
  },
  inptit(e) {
    const { value } = e.detail;
    const { index } = e.currentTarget.dataset;
    const { form } = this.data;
    form[index].title = value;
    this.setData({ form });
  },
  inpkey(e) {
    const { value } = e.detail;
    const { index, indexs } = e.currentTarget.dataset;
    const { form } = this.data;
    form[index].item[indexs].key = value;
    this.setData({ form });
  },
  inpval(e) {
    const { value } = e.detail;
    const { index, indexs } = e.currentTarget.dataset;
    const { form } = this.data;
    form[index].item[indexs].value = value;
    this.setData({ form });
  },
  addform_item(e) {
    const { index, indexs } = e.currentTarget.dataset;
    const { form } = this.data;
    const item = { key: "", value: "" };
    form[index].item.splice(indexs + 1, 0, item);
    this.setData({ form });
  },
  cutform_item(e) {
    const { index, indexs } = e.currentTarget.dataset;
    const { form } = this.data;
    form[index].item.splice(indexs, 1);
    this.setData({ form });
  },
  obj() {
    const { form } = this.data;
    const info = {};
    form.forEach((e) => {
      const is = {};
      e.item.forEach((v) => {
        is[v.key] = v.value;
      });
      info[e.title] = is;
    });
    return info;
  },
});
